package com.dangdang.service;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.dangdang.domain.ReceiveAddress;
import com.dangdang.util.HbnUtils;

/**
 * 
 * 
 * @author Wangpeihu
 * @team [Never give up]
 * @since JDK1.6(建议)
 * @date 2010-1-30
 */
public class UserServiceImpl implements UserService {

	/**
	 * 根据用户 ID 获取该用户的收货地址
	 */
	@SuppressWarnings("unchecked")
	public List<ReceiveAddress> findAddressByUserId(Integer userId) {
		Session session = HbnUtils.getSession();
		Query query = session.createQuery("from ReceiveAddress where userId=?");
		query.setParameter(0, userId);
		List<ReceiveAddress> receiveAddressList = query.list();
		session.close();
		return receiveAddressList;
	}

	public static void main(String[] args) {
		ReceiveAddress receiveAddress = new ReceiveAddress();
		receiveAddress.setFullAddress("合肥工业大学附近");
		receiveAddress.setId(1);
		receiveAddress.setMobile("15209831398");
		receiveAddress.setPhone("0551-5534537");
		receiveAddress.setPostalCode("110112");
		receiveAddress.setReceiveName("王培虎");
		receiveAddress.setUserId(1);
		Session session = HbnUtils.getSession();
		try {
			session.beginTransaction();
			session.save(receiveAddress);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		} finally {
			session.close();
		}
	}

	/**
	 * 添加一个用户的收获地址
	 */
	public void addAddress(ReceiveAddress receiveAddress, Integer userId) {
		receiveAddress.setUserId(userId);
		Session session = HbnUtils.getSession();
		try {
			session.beginTransaction();
			session.save(receiveAddress);
			session.getTransaction().commit();
		} catch (Exception e) {
			session.getTransaction().rollback();
		} finally {
			session.close();
		}

	}
}
